package com.yoj.judgeservice.codesandbox;

import cn.hutool.extra.spring.SpringUtil;
import com.yoj.judgeservice.codesandbox.impl.RemoteCodeSandbox;
import com.yoj.judgeservice.config.CodeSandboxProperties;
import com.yoj.model.enums.CodeSandboxEnum;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 代码沙箱工厂（根据沙箱类型枚举对象创建指定的代码沙箱实例）
 */
@Slf4j
@Data
@Service
public class CodeSandboxFactory {

    // key: CodeSandbox 实现类类名，value: CodeSandbox 实现类Bean对象
    private final Map<String, CodeSandbox> codeSandboxMap;

    @Resource
    private CodeSandboxProperties codeSandboxProperties;

    @Autowired
    public CodeSandboxFactory(Map<String, CodeSandbox> codeSandboxMap) {
        this.codeSandboxMap = codeSandboxMap;
    }

    public CodeSandbox newInstance() {
        // 从配置文件读取沙箱类型
        CodeSandboxEnum type = CodeSandboxEnum.getEnumByValue(codeSandboxProperties.getType());
        assert type != null;
        return newInstance(type);
    }

    /**
     * 创建代码沙箱实例
     * @param type 沙箱类型枚举
     * @return 指定类型的沙箱实例
     */
    public CodeSandbox newInstance(CodeSandboxEnum type) {
        // 处理类型
        String typeString = type.getValue() + "CodeSandbox";
        return codeSandboxMap.getOrDefault(typeString, SpringUtil.getBean(RemoteCodeSandbox.class));
    }

}